﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;


public partial class BookingManage_BookedListForCpm : BasePage
{
    IBNBookingHandler bookingManager = new BNBookingHandler();
    DataBase db = new DataBase();
    private static bool isCancel = false;
    private static bool isArrange = false;
    string language = "";
    private static string chkSelectedForArrange = "";
    private bool isCpmRole2 = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        ISystemHandler sysManage = new SystemHandler();
        isCpmRole2 = sysManage.IsCompanyRoles2();
        language = Thread.CurrentThread.CurrentUICulture.ToString().ToLower();
        if (!"0".Equals(Session["LoginUserClientID"].ToString()) && !isCpmRole2)
        {
            Response.Redirect("BookedList.aspx");
        }
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1048"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    //判断用户有没有分配Booking权限
                    if (strPermission.Contains("1051"))
                    {
                        isArrange = true;
                        lbtnArrange.Visible = true;
                    }
                    else
                    {
                        isArrange = false;
                        lbtnArrange.Visible = false;
                    }
                    //判断用户有没有取消Booking权限
                    if (strPermission.Contains("1049"))
                    {
                        lbtnCancelBooking.Visible = true;
                        isCancel = true;
                    }
                    else
                    {
                        lbtnCancelBooking.Visible = false;
                        isCancel = false;
                    }
                    //判断有没有取消分配的权限 
                    if (strPermission.Contains("1052"))
                    {
                        lbtnCancelArrange.Visible = true;
                    }
                    else
                    {
                        lbtnCancelArrange.Visible = false;
                    }
                }
            }

            lbtnCancelBooking.Attributes.Add("OnClick", "javascript:return confirm('" + Resources.Messages.CancelRecord + "');");
            ViewState["OrderBy"] = "DefaultSort asc, PKID";
            ViewState["Accending"] = "desc";
            dataBind();
            initSearchBox();
        }
    }

    private void initSearchBox()
    {
        fillShipper();
        fillWhouse();
        fillFactory();
    }

    private void fillShipper()
    {
        ISyClientHandler clientManager = new SyClientHandler();

        DataTable dt = clientManager.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();

    }

    private void fillWhouse()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = "SELECT DISTINCT client.* FROM Sy_Client client " +
                        " inner join Sy_ClientType type on client.PKID = type.ClientID " +
                        " inner join Sy_Code code on type.SyCodeID = code.PKID" +
                        " where code.Type='CT' and (code.Code = 'MT' or code.Code = 'CK') and client.Status = 1";
        DataTable dt = clientManager.GetClientList(sqlStr, null);
        ddlWhouse.DataSource = dt;
        ddlWhouse.DataTextField = ("en".Equals(language) ? "ENGShortName" : ("zh-hk".Equals(language) ? "HKShortName" : "CNShortName"));
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem("select...", "0"));
    }

    private void fillFactory()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        DataTable dt = clientManager.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        lstFactory.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstFactory.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstFactory.DataTextField = "HKShortName";
        }
        else
        {
            lstFactory.DataTextField = "CNShortName";
        }
        lstFactory.DataValueField = "PKID";
        lstFactory.DataBind();
    }

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        
        if (ViewState["Shipper"] != null)
        {
            sqlstr += " and (dtl.ShipperID in (" + ViewState["Shipper"] + ")) ";
        }
        if (ViewState["Factory"] != null)
        {
            sqlstr += " and (vendor.PKID in (" + ViewState["Factory"] + "))";
        }
        if (ViewState["Whouse"] != null)
        {
            list.Add(new SqlParameter("@Whouse", ViewState["Whouse"].ToString()));
            sqlstr += " and dtl.WhouseID = @Whouse";
        }
        if (ViewState["WinStart"] != null)
        {
            list.Add(new SqlParameter("@WinStart", ViewState["WinStart"].ToString()));
            sqlstr += " and dtl.WinStart = @WinStart";
        }
        if (ViewState["WinClose"] != null)
        {
            list.Add(new SqlParameter("@WinClose", ViewState["WinClose"].ToString()));
            sqlstr += " and dtl.WinClose = @WinClose";
        }
        if (ViewState["JobDate"] != null)
        {
            list.Add(new SqlParameter("@JobDate", ViewState["JobDate"].ToString()));
            sqlstr += " and dtl.JobDate = @JobDate";
        }

        parms = list.ToArray();
    }

    private void dataBind()
    {
        DataTable dt = getSearchData();
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvBookedList.DataSource = view;
        gvBookedList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private DataTable getSearchData()
    {
        string sqlStr = @"SELECT booking.PKID as BID, booking.Status,dtl.*,client.CNShortName as Whouse, client.HKShortName as HKWhouse, 
                            client.ENGShortName as ENGWhouse, shipper.CNShortName as Shipper,
                            shipper.HKShortName as HKShipper, shipper.ENGShortName as ENGShipper,
                            vendor.CNShortName as Vendor, vendor.HKShortName as HKVendor, vendor.ENGShortName as ENGVendor,
                            contractor.CNShortName as CNContractor, contractor.HKShortName as HKContractor,
                            contractor.ENGShortName as ENGContractor, bnDtl.Status as BNDtlStatus,
                            (CASE WHEN bnDtl.Status = 6 THEN 100 else bnDtl.Status END) AS DefaultSort,
                            vendor.PKID as fid
                        FROM BN_Booking booking inner join 
                            BN_BookingDtl dtl on booking.PKID = dtl.BookingID LEFT JOIN
                            Sy_Client client ON dtl.WhouseID = client.PKID LEFT JOIN
                            Sy_Client vendor ON booking.VendorID = vendor.PKID LEFT JOIN
                            Sy_Client contractor ON dtl.Contractor = contractor.PKID LEFT JOIN
                            Sy_Client shipper ON dtl.ShipperID = shipper.PKID INNER JOIN
                            BN_BookingNoteDtl bnDtl ON dtl.BookingNoteDtlID = bnDtl.PKID
                        WHERE dtl.JobDate IS NOT NULL ";
        if (isCpmRole2)
        {
            sqlStr += " and (booking.BookingUser in (select UserID from Users where ClientID = " + Session["LoginUserClientID"].ToString() + ")) ";
        }
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        return bookingManager.GetList(sqlStr, parms);
    }

    protected void gvBookedList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvBookedList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvBookedList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dataBind();
    }
    protected void gvBookedList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        buildSearchCondition();

        dataBind();

        setFactoryByCondition();
    }

    private void buildSearchCondition()
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }
        if (lstSelFactory.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelFactory.Items.Count; i++)
            {
                item += lstSelFactory.Items[i].Value + ",";
            }
            ViewState["Factory"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Factory"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {
            ViewState["Whouse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whouse"] = null;
        }
        if (txtWinStart.Text != null && txtWinStart.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtWinStart.Text.Trim());
                ViewState["WinStart"] = txtWinStart.Text.Trim();
            }
            catch { ViewState["WinStart"] = null; }
        }
        else
        {
            ViewState["WinStart"] = null;
        }
        if (txtWinClose.Text != null && txtWinClose.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtWinClose.Text.Trim());
                ViewState["WinClose"] = txtWinClose.Text.Trim();
            }
            catch { ViewState["Winclose"] = null; }
        }
        else
        {
            ViewState["WinClose"] = null;
        }
        if (txtSJobDate.Text != null && txtSJobDate.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtSJobDate.Text.Trim());
                ViewState["JobDate"] = txtSJobDate.Text.Trim();
            }
            catch { ViewState["txtSJobDate"] = null; }
        }
        else
        {
            ViewState["JobDate"] = null;
        }
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvBookedList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void gvBookedList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblShipper = (Label)e.Row.FindControl("lblShipper");
            Label lblHKShipper = (Label)e.Row.FindControl("lblHKShipper");
            Label lblENGShipper = (Label)e.Row.FindControl("lblENGShipper");

            Label lblWhouse = (Label)e.Row.FindControl("lblWhouse");
            Label lblHKWhouse = (Label)e.Row.FindControl("lblHKWhouse");
            Label lblENGWhouse = (Label)e.Row.FindControl("lblENGWhouse");

            Label lblVendor = (Label)e.Row.FindControl("lblVendor");
            Label lblHKVendor = (Label)e.Row.FindControl("lblHKVendor");
            Label lblENGVendor = (Label)e.Row.FindControl("lblENGVendor");

            Label lblContractor = (Label)e.Row.FindControl("lblContractor");
            Label lblHKContractor = (Label)e.Row.FindControl("lblHKContractor");
            Label lblENGContractor = (Label)e.Row.FindControl("lblENGContractor");

            if ("en".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = true;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = true;

                lblVendor.Visible = false;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = true;

                lblContractor.Visible = false;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = true;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = true;
                lblENGWhouse.Visible = false;

                lblVendor.Visible = false;
                lblHKVendor.Visible = true;
                lblENGVendor.Visible = false;

                lblContractor.Visible = false;
                lblHKContractor.Visible = true;
                lblENGContractor.Visible = false;
            }
            else
            {
                lblShipper.Visible = true;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = true;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = false;

                lblVendor.Visible = true;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = false;

                lblContractor.Visible = true;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = false;
            }
        }
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvBookedList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvBookedList.PageCount)
            {
                this.gvBookedList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            bool isDateTime = false;
            Regex reg = new Regex("((1[89]\\d{2})|([2-8]\\d{3}))[-](([1][012])|(0{1}[1-9]))[-]((3[01])|([12]\\d)|(0{1}[1-9]))");
            isDateTime = reg.IsMatch(txtNewJobDate.Text.Trim());
            reg = new Regex("(([0][0-9])|([1][0-9])|([2][0-3]))([0-5][0-9])");
            string h = txtNewJobDateH.Text.Trim();
            h = h.Replace(":", "");
            isDateTime = isDateTime && reg.IsMatch(h);

            if (isDateTime)
            {
                string jobDate = txtNewJobDate.Text.Trim() + StringUtil.GetTime(txtNewJobDateH.Text.Trim());
                string[] dtlIds = Request["chkSelected"].ToString().Split(',');
                string userName = Session["UserName"].ToString();
                object userId = Session["UserID"];
                foreach (string dtlId in dtlIds)
                {
                    if (!bookingManager.UpdateDetail(int.Parse(dtlId), jobDate, userName, userId, true))
                    {
                        Jscript.AlertInAjax(Resources.Messages.UpdateFailed, UpdatePanel1);
                        return;
                    }
                }
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongDateTimeFormat, UpdatePanel1);
            }
            dataBind();
        }
    }

    protected void lbtnCancelBooking_Click(object sender, EventArgs e)
    {
        if (!isCancel)
        {
            Response.Redirect("~/NotPurview.aspx");
        }

        if (Request["chkSelected"] != null)
        {
            string[] ids = Request["chkSelected"].ToString().Split(',') ;
            int userId = int.Parse(Session["UserID"].ToString());
            string userName = Session["UserName"].ToString();
            IBNBookingNoteHandler bnManager = new BNBookingNoteHandler();
            foreach (string dtlid in ids)
            {
                BN_BookingDtlQuery dtlQuery = bookingManager.GetBookingDtlByDtlID(int.Parse(dtlid));
                //BN_BookingQuery query = bookingManager.GetBookingByID(dtlQuery.BookingID);
                BN_BookingNoteDtlQuery bnDtlQuery = bnManager.GetBookingNoteDetailByID(dtlQuery.BookingNoteDtlID);

                //if (query.Status == int.Parse(HK2009.Common.Enums.BookingStatus.NEW.ToString("d")) || query.Status == int.Parse(HK2009.Common.Enums.BookingStatus.CANCELARRANGED.ToString("d")))
                if (bnDtlQuery != null && (bnDtlQuery.Status == int.Parse(HK2009.Common.Enums.BookingNoteDtlStatus.BOOKING.ToString("d")) ||
                    bnDtlQuery.Status == int.Parse(HK2009.Common.Enums.BookingNoteDtlStatus.CANCELARRANGE.ToString("d")) ||
                    bnDtlQuery.Status == int.Parse(HK2009.Common.Enums.BookingNoteDtlStatus.CCANCEL.ToString("d"))))
                {
                    string sqlStr = @"UPDATE BN_Booking SET Status = @BookingStatus, CancelUser = @CancelUser, CancelDate = GETDATE() WHERE PKID = @PKID;
                                  UPDATE BN_BookingNoteDtl SET Status = @DtlStatus, CancelUser = @CancelUser, CancelDate = GETDATE()
                                  WHERE PKID IN (
                                  SELECT DISTINCT BookingNoteDtlID FROM BN_BookingDtl WHERE BookingID = @PKID)";
                    SqlParameter[] parms = new SqlParameter[4];
                    parms[0] = new SqlParameter("@BookingStatus", HK2009.Common.Enums.BookingStatus.CANCEL.ToString("d"));
                    //parms[1] = new SqlParameter("@PKID", query.PKID);
                    parms[1] = new SqlParameter("@PKID", dtlQuery.BookingID);
                    parms[2] = new SqlParameter("@DtlStatus", HK2009.Common.Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"));
                    parms[3] = new SqlParameter("@CancelUser", userId);
                    
                    // 取消Booking的同时清空JobDate，发邮件通知
                    bookingManager.UpdateBookingStatus(sqlStr, parms);
                    if (!bookingManager.UpdateDetail(dtlQuery.PKID, "", userName, userId, true))
                    {
                        Jscript.AlertInAjax(Resources.Messages.CancelFailed, UpdatePanel1);
                        break;
                    }
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.WrongStatus, UpdatePanel1);
                }
            }

            dataBind();
        }
    }

    protected void lbtnArrange_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] == null)
        {
            Jscript.AlertInAjax("no selected booking", UpdatePanel1);
            return;
        }

        if (!isArrange)
        {
            Response.Redirect("~/NotPurview.aspx");
        }

        if (!isAbleToArrange(Request["chkSelected"]))
        {
            Jscript.AlertInAjax("Booking" + Resources.Messages.WrongStatus, UpdatePanel1);
            return;
        }

        chkSelectedForArrange = Request["chkSelected"].ToString();

        myDiv.Style.Add("display", "block");
        divError.Style.Add("display", "block");

        ddlCContractor.Items.Clear();
        ddlCContractor.DataSource = getBindContractor();
        ddlCContractor.DataValueField = "PKID";
        if ("en".Equals(language))
        {
            ddlCContractor.DataTextField = "ENGShortName";
        }
        else if ("zh-hk".Equals(language))
        {
            ddlCContractor.DataTextField = "HKShortName";
        }
        else
        {
            ddlCContractor.DataTextField = "CNShortName";
        }
        ddlCContractor.DataBind();
        ddlCContractor.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }

    private bool isAbleToArrange(object chkSelected)
    {
        string[] ids = chkSelected.ToString().Split(',');
        IBNBookingNoteHandler bnManager = new BNBookingNoteHandler();

        foreach (string id in ids)
        {
            BN_BookingDtlQuery dtlQuery = bookingManager.GetBookingDtlByDtlID(int.Parse(id));
            if (dtlQuery != null)
            {
                //BN_BookingQuery query = bookingManager.GetBookingByID(dtlQuery.BookingID);
                BN_BookingNoteDtlQuery query = bnManager.GetBookingNoteDetailByID(dtlQuery.BookingNoteDtlID);
                if (query != null)
                {
                    //if (query.Status.ToString() != HK2009.Common.Enums.BookingStatus.NEW.ToString("d") && query.Status.ToString() != HK2009.Common.Enums.BookingStatus.CANCELARRANGED.ToString("d"))
                    if (query.Status.ToString() != HK2009.Common.Enums.BookingNoteDtlStatus.BOOKING.ToString("d") &&
                        query.Status.ToString() != HK2009.Common.Enums.BookingNoteDtlStatus.CANCELARRANGE.ToString("d") &&
                        query.Status.ToString() != HK2009.Common.Enums.BookingNoteDtlStatus.CCANCEL.ToString("d"))
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    private DataTable getBindContractor()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = "SELECT client.* FROM Sy_Client client " +
                        " inner join Sy_ClientType type on client.PKID = type.ClientID " +
                        " inner join Sy_Code code on type.SyCodeID = code.PKID" +
                        " where code.Type='CT' and code.Code = 'TCGS' and client.Status = 1";

        DataTable dt = clientManager.GetClientList(sqlStr, null);
        return dt;
    }

    /// <summary>
    /// 执行分配运输队
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCSubmit_Click(object sender, EventArgs e)
    {
        lblCError.Visible = false;
        if ("0".Equals(ddlCContractor.SelectedValue))
        {
            lblCError.Visible = true;
            return;
        }

        int cid = int.Parse(ddlCContractor.SelectedValue);
        if (doArrange(cid))
        {
            myDiv.Style.Add("display", "none");
            divError.Style.Add("display", "none");
            dataBind();
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.ArrangeFailed, UpdatePanel1);
        }
    }

    protected void btnCClose_Click(object sender, EventArgs e)
    {
        myDiv.Style.Add("display", "none");
        divError.Style.Add("display", "none");
    }

    protected void lbtnCancelArrange_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            List<BN_BookingQuery> bookings = new List<BN_BookingQuery>();
            string[] ids = Request["chkSelected"].ToString().Split(',');
            //int arrangedStatus = int.Parse(HK2009.Common.Enums.BookingStatus.ARRANGED.ToString("d"));
            int arrangedStatus = int.Parse(HK2009.Common.Enums.BookingNoteDtlStatus.ARRANGED.ToString("d"));
            IBNBookingNoteHandler bnManager = new BNBookingNoteHandler();
            foreach (string id in ids)
            {
                BN_BookingDtlQuery dtlQuery = bookingManager.GetBookingDtlByDtlID(int.Parse(id));
                if (dtlQuery != null)
                {
                    //BN_BookingQuery query = bookingManager.GetBookingByID(dtlQuery.BookingID);
                    BN_BookingNoteDtlQuery query = bnManager.GetBookingNoteDetailByID(dtlQuery.BookingNoteDtlID);
                    if (query != null)
                    {
                        if (query.Status != arrangedStatus)
                        {
                            Jscript.AlertInAjax(Resources.Messages.WrongStatus, UpdatePanel1);
                            return;
                        }

                        BN_BookingQuery bkquery = bookingManager.GetBookingByID(dtlQuery.BookingID);
                        bookings.Add(bkquery);
                    }
                }
            }

            foreach (BN_BookingQuery tmp in bookings)
            {
                string sqlStr = @"SELECT * FROM BN_ShippingOrder WHERE BookingID=@BookingID AND
                                Status != @Status0 AND Status != @Status4 AND Status != @Status6 and Status!=@Status8";
                SqlParameter[] parms = new SqlParameter[8];
                parms[0] = new SqlParameter("@BookingID", tmp.PKID);
                parms[1] = new SqlParameter("@Status0", HK2009.Common.Enums.ShippingOrderStatus.NEW.ToString("d"));
                parms[2] = new SqlParameter("@Status4", HK2009.Common.Enums.ShippingOrderStatus.CANCEL.ToString("d"));
                parms[3] = new SqlParameter("@Status6", HK2009.Common.Enums.ShippingOrderStatus.CANCELARRANGE.ToString("d"));
                parms[4] = new SqlParameter("Status8", HK2009.Common.Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d"));
                DataTable dt = bookingManager.GetList(sqlStr, parms);

                if (dt != null && dt.Rows.Count > 0)
                {
                    Jscript.AlertInAjax("该Booking分配的运输队已确认Job，请通知其取消后才能取消分配!", UpdatePanel1);
                    return;
                }

                sqlStr = @"UPDATE BN_ShippingOrder SET Status = @SOStatus, CancelArrangeUser = @CAUser, CancelArrDate = GETDATE() 
                            WHERE BookingID = @BookingID;
                           UPDATE BN_Booking SET Status = @BookingStatus, CAUser = @CAUser, CADate = GETDATE()
                            WHERE PKID = @BookingID;
                           UPDATE BN_BookingNoteDtl SET Status = @BNDStatus, CancelArrangeUser=@CAUser,CancelArrDate=GETDATE()
                            WHERE PKID IN(SELECT DISTINCT BookingNoteDtlID FROM BN_BookingDtl WHERE BookingID=@BookingID)";
                parms = new SqlParameter[5];
                parms[0] = new SqlParameter("@SOStatus", HK2009.Common.Enums.ShippingOrderStatus.CANCELARRANGE.ToString("d"));
                parms[1] = new SqlParameter("@CAUser", int.Parse(Session["UserID"].ToString()));
                parms[2] = new SqlParameter("@BookingID", tmp.PKID);
                parms[3] = new SqlParameter("@BNDStatus", HK2009.Common.Enums.BookingNoteDtlStatus.CANCELARRANGE.ToString("d"));
                parms[4] = new SqlParameter("@BookingStatus", HK2009.Common.Enums.BookingStatus.CANCELARRANGED.ToString("d"));

                if (!bookingManager.BookingCancelArrange(sqlStr, parms))
                {
                    Jscript.AlertInAjax(Resources.Messages.CancelFailed, UpdatePanel1);
                    dataBind();
                    return;
                }
            }
            dataBind();
        }
    }

    private bool doArrange(int contractorId)
    {
        try
        {
            if (!isAbleToArrange(chkSelectedForArrange))
            {
                Jscript.AlertInAjax("Booking" + Resources.Messages.WrongStatus, UpdatePanel1);
                return false;
            }

            //List<string> sqls = new List<string>();
            StringBuilder sqls = new StringBuilder();
            List<SqlParameter> paramList = new List<SqlParameter>();
            int userId = int.Parse(Session["UserID"].ToString());
            string[] ids = chkSelectedForArrange.Split(',');
            List<CTmpAppointment> appointments = new List<CTmpAppointment>();
            string format = "yyyy-MM-dd hh:mm:ss";

            paramList.Add(new SqlParameter("@Status", HK2009.Common.Enums.BookingStatus.ARRANGED.ToString("d")));
            paramList.Add(new SqlParameter("@ArrangeUser", userId.ToString()));
            paramList.Add(new SqlParameter("@Contractor", contractorId));
            paramList.Add(new SqlParameter("@NewOrderStatus", int.Parse(HK2009.Common.Enums.ShippingOrderStatus.NEW.ToString("d"))));
            paramList.Add(new SqlParameter("@BNDtlStatus", HK2009.Common.Enums.BookingNoteDtlStatus.ARRANGED.ToString("d")));

            foreach (string id in ids)
            {
                BN_BookingDtlQuery dtlQuery = bookingManager.GetBookingDtlByDtlID(int.Parse(id));
                if (dtlQuery != null)
                {
                    BN_BookingQuery query = bookingManager.GetBookingByID(dtlQuery.BookingID);
                    if (query != null)
                    {
                        string appointMent = string.Empty;
                        if (ISMATorFP(query.PKID))
                        {
                            string jobdate = dtlQuery.JobDate.ToString(format);
                            foreach (CTmpAppointment tmpAm in appointments)
                            {
                                if (tmpAm.JobDate.Equals(jobdate))
                                {
                                    appointMent = tmpAm.Appointment;
                                    break;
                                }
                            }
                            if (appointMent == string.Empty)
                            {
                                appointMent = bookingManager.GetAppointament(jobdate);
                                CTmpAppointment cta = new CTmpAppointment(jobdate, appointMent);
                                appointments.Add(cta);
                            }

                        }
                        if (appointMent == string.Empty)
                        {
                            appointMent = "";
                        }

                        sqls.Append("UPDATE BN_Booking SET Status=@Status, ArrangeUser=@ArrangeUser, ArrangeDate=GETDATE() WHERE PKID=@BookingID" + query.PKID + ";");
                        paramList.Add(new SqlParameter("@BookingID" + query.PKID, query.PKID));

                        // 添加BN_ShippingOrder和BN_ShippingOrderDtl
                        sqls.Append(@"INSERT INTO BN_ShippingOrder(Contractor, OrderNO, BookingID, BookingNO, BookingDate,
                                            Status, VendorID, ArrangeUser, ArrangeDate, Appointament) 
                                            VALUES(@Contractor,dbo.Fn_NextOrderNO(), @BookingID" + query.PKID + ", @BookingNO" + query.PKID + ", @BookingDate" + query.PKID + @",
                                            @NewOrderStatus, @VendorID" + query.PKID + @", @ArrangeUser, GETDATE(),@Appointment" + query.PKID + @");
                                          SET @ReturnValue" + query.PKID + @"=@@Identity;");
                        paramList.Add(new SqlParameter("@BookingNO" + query.PKID, query.BookingNO));
                        paramList.Add(new SqlParameter("@BookingDate" + query.PKID, query.BookingDate));
                        paramList.Add(new SqlParameter("@VendorID" + query.PKID, query.VendorID));
                        paramList.Add(new SqlParameter("@Appointment" + query.PKID, appointMent));

                        sqls.Append(@"INSERT INTO BN_ShippingOrderDtl(OrderID, BookingDtlID, ShipperID, SONO, PNNO, WinStart, WinClose, JobDate,
                                           DeliveryDate, WhouseID, FCLLCL, ItemNO, PCS, CTN, GrossWT, VOL, Remark,PlaceID)
                                    SELECT @ReturnValue" + query.PKID + @", dtl.PKID, dtl.ShipperID, dtl.SONO, dtl.PNNO, dtl.WinStart, 
                                           dtl.WinClose, dtl.JobDate,
                                           dtl.DeliveryDate, dtl.WhouseID, dtl.FCLLCL, dtl.ItemNO, dtl.PCS, dtl.CTN, dtl.GrossWT, dtl.VOL, dtl.Remark,dtl.PlaceID
                                    FROM BN_BookingDtl dtl
                                    WHERE dtl.PKID = @BookingDtlID" + query.PKID +";");
                        paramList.Add(new SqlParameter("@ReturnValue" + query.PKID, "000000000000000000"));
                        paramList.Add(new SqlParameter("@BookingDtlID" + query.PKID, dtlQuery.PKID));

                        // 更新BN_BookingNoteDtl表的Status和BN_BookingDtl表的Contractor
                        sqls.Append(@"UPDATE BN_BookingDtl SET Contractor=@Contractor, Appointament=@Appointment" + query.PKID
                                    + " WHERE PKID=@BookingDtlID" + query.PKID + ";");
                        sqls.Append(@"UPDATE BN_BookingNoteDtl SET Status=@BNDtlStatus,ArrangeUser=@ArrangeUser, ArrangeDate=GETDATE(),Appointament=@Appointment" + query.PKID + @" WHERE PKID=(
                                            SELECT BookingNoteDtlID FROM BN_BookingDtl WHERE PKID=@BookingDtlID" + query.PKID + ");");
                        
                    }
                }
            }

            if (bookingManager.BookingArrange2(sqls.ToString(), paramList.ToArray()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// 判断传过来的Booking的托运人是否是MAT或者FP
    /// </summary>
    /// <returns></returns>
    private bool ISMATorFP(int bookingID)
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sql = @"SELECT shipper.* FROM Sy_Client shipper INNER JOIN
                            BN_BookingDtl bookingDtl ON shipper.PKID = bookingDtl.ShipperID
                        WHERE shipper.ENGShortName != 'MAT' AND shipper.ENGShortName != 'FP' AND
                            bookingDtl.BookingID = @BookingID";
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@BookingID", bookingID);
        DataTable dt = clientManager.GetClientList(sql, parms);

        if (dt != null && dt.Rows.Count > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    protected void btnAddSShipper_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }

            setFactoryByCondition();
        }
        else
        {

        }

    }
    protected void btnDeleteSShipper_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

            setFactoryByCondition();
        }
    }

    protected void btnAddSFactory_Click(object sender, EventArgs e)
    {
        if (lstFactory.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstFactory.Items.Count; i++)
            {
                bool issel = false;
                if (lstFactory.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelFactory.Items.Count; j++)
                    {
                        if (lstFactory.Items[i].Value == lstSelFactory.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstFactory.Items[i].Text;
                        item.Value = lstFactory.Items[i].Value;
                        lstSelFactory.Items.Add(item);
                    }
                }
            }

            setFactoryByCondition();
        }
        else
        {

        }

    }
    protected void btnDeleteFactory_Click(object sender, EventArgs e)
    {
        if (lstSelFactory.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelFactory.Items.Count; i++)
            {
                if (!lstSelFactory.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelFactory.Items[i].Text, lstSelFactory.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelFactory.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelFactory.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelFactory.Items.Clear();
            }

            setFactoryByCondition();
        }

    }

    private void setFactoryByCondition()
    {
        buildSearchCondition();
        DataTable dt = getSearchData();

        DataTable dtFactory = dt.Clone();
        dtFactory.Rows.Clear();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            bool isExists = false;
            for (int j = 0; j < dtFactory.Rows.Count; j++)
            {
                if (dt.Rows[i]["fid"].ToString().Equals(dtFactory.Rows[j]["fid"].ToString()))
                {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
            {
                dtFactory.ImportRow(dt.Rows[i]);
            }
        }

        lstFactory.DataSource = null;
        lstFactory.DataBind();

        lstFactory.DataSource = dtFactory;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstFactory.DataTextField = "ENGVendor";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstFactory.DataTextField = "HKVendor";
        }
        else
        {
            lstFactory.DataTextField = "Vendor";
        }
        lstFactory.DataValueField = "fid";
        lstFactory.Items.Clear();
        lstFactory.DataBind();

    }
}